﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KKU.RBSFPP.Shared.DAC;

namespace KKU.RBSFPP.Web.Administrator.Controllers
{
    [Authorize]
    public class SellController : Controller
    {
        private RBSFPPModelContainer db = new RBSFPPModelContainer();

        //
        // GET: /Sell/

        public ActionResult Index()
        {
            //var producttrackings = db.ProductTrackings.Include("Product").Include("ProductPricingPerUnit").Include("Member");
            //return View(producttrackings.ToList());

            var now = DateTime.Today;

            var result = from it in db.ProductTrackings.Include("Product").Include("ProductpricingPerUnit").Include("Member")
                         where (it.CreateOn.Day == now.Day) && (it.CreateOn.Month == now.Month) && (it.CreateOn.Year == now.Year)
                         && it.Action == "S"
                         && it.DeleteOn.HasValue == false
                         select it;

            //ยอดขายในวันนี้
            if (result.Any())
            {
                var totalprice = result.Sum(it => it.Unit * it.ProductPricingPerUnit.SellingPrice);
                ViewBag.Summary = totalprice.ToString("C2");
            }

            else 
            {
                var zero = 0;
                ViewBag.Summary = zero.ToString("C2");
            }
            return View(result.ToList());


           
        }

        //
        // GET: /Sell/Details/5

        public ActionResult Details(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            return View(producttracking);
        }

        //
        // GET: /Sell/Create

        public ActionResult Create()
        {
            //สร้างตะกร้าเก็บสินค้า
            var cart = new List<ProductTracking>();
            TempData["Cart"] = cart;
            ViewBag.Cart = cart;

            //เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username");
            return View();
        }

        //
        // POST: /Sell/Create

        [HttpPost]
        public ActionResult AddMoreItem(ProductTracking producttracking)
        { 
            var cart = TempData["Cart"] as List<ProductTracking>;
            //เอาข้อมูลที่่เลือกเก็บไว้ในตระกร้าสินค้า
            if (ModelState.IsValid)
            {
                producttracking.Product = db.Products.FirstOrDefault(it => it.Id == producttracking.ProductId);
                producttracking.ProductPricingPerUnit = db.Products.FirstOrDefault(it => it.Id == producttracking.ProductId).ProductPricingPerUnit;

                if (cart.Any(it => it.ProductId == producttracking.ProductId))
                {
                    var item = cart.FirstOrDefault(it => it.ProductId == producttracking.ProductId);
                    item.Unit += producttracking.Unit;
                }
                else
                {
                    cart.Add(producttracking);
                }
            }

            TempData["Cart"] = cart;
            ViewBag.Cart = cart;

            //เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "UserName");
            ViewBag.Summary = cart.Sum(it => it.Unit * it.ProductPricingPerUnit.SellingPrice);
            return View("Create");
        }

        public ActionResult RemoveItem(int id)
        {
            // เอาสินค้าที่ต้องการออกจากตระกร้า
            var cart = TempData["Cart"] as List<ProductTracking>;
            if (cart.Count > id)
            {
                cart.RemoveAt(id);
            }
            TempData["Cart"] = cart;
            ViewBag.Cart = cart;

            // เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username");
            ViewBag.Summary = cart.Sum(it => it.Unit * it.ProductPricingPerUnit.SellingPrice);
            return View("Create");
        }
        [HttpPost]
        public ActionResult Confirm()
        {
            //เอาสินค้าจากตระกร้าไปเก็บลงฐานข้อมูล
            var cart = TempData["Cart"] as List<ProductTracking>;
            if (cart.Any())
            {
                var now = DateTime.Now;
                foreach (var item in cart)
                { 
                    var newRecord = new ProductTracking
                    {
                        Action = "S",
                        CreateOn = now,
                        ProductPricingPerUnitId = db.Products.Where(it => it.Id == item.ProductId).Select(it => it.ProductPricingPerUnitId).FirstOrDefault(),
                        MemberId = db.Members.Where(it => it.Username == User.Identity.Name).FirstOrDefault().Id,
                        ProductId = item.ProductId,
                        Unit = item.Unit
                    };
                    db.ProductTrackings.AddObject(newRecord);
                }
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }


        //[HttpPost]
        //public ActionResult Create(ProductTracking producttracking)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        producttracking.Action = "S";
        //        producttracking.CreateOn = DateTime.Now;

        //        {
        //            var productQry = from it in db.Products
        //                             where it.Id == producttracking.ProductId
        //                             select it.ProductPricingPerUnitId;
        //            producttracking.ProductPricingPerUnitId = productQry.FirstOrDefault();
        //        }

        //        {
        //            var userQry = from it in db.Members
        //                          where it.Username == User.Identity.Name
        //                          select it;
        //            producttracking.Member = userQry.FirstOrDefault();
                
        //        }


        //        db.ProductTrackings.AddObject(producttracking);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }

        //    ViewBag.ProductId = new SelectList(db.Products, "Id", "Name", producttracking.ProductId);
        //    ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits, "Id", "Name", producttracking.ProductPricingPerUnitId);
        //    ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
        //    return View(producttracking);
        //}

        //
        // GET: /Sell/Edit/5

        public ActionResult Edit(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
            return View(producttracking);
        }

        //
        // POST: /Sell/Edit/5

        [HttpPost]
        public ActionResult Edit(ProductTracking producttracking)
        {
            if (ModelState.IsValid)
            {
                db.ProductTrackings.Attach(producttracking);
                db.ObjectStateManager.ChangeObjectState(producttracking, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
            return View(producttracking);
        }

        //
        // GET: /Sell/Delete/5

        public ActionResult Delete(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            return View(producttracking);
        }

        //
        // POST: /Sell/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            db.ProductTrackings.DeleteObject(producttracking);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}